import { t } from 'i18next'
import { fetchGetVideoInfo, fetchStartVideo, fetchUpdateSaveVideo } from '@/api/manager/mccMtVideo'
import {
	FetchGetVideoInfoReturnProps,
	FetchStartVideoParamsProps,
	FetchUpdateSaveVideoParamsProps,
	MtVideosProps,
} from '@/api/manager/mccMtVideo/interface'
import Alert from '@/components/Alert'
import { useMccStore } from '@/pages/manager/store'
import { buildNameTime, formatSeconds, replaceSpaceBk } from '@/utils/format'
import { Button, CheckBox, Form, FormItem, InnerInputRef, Input, Modal, Select } from '@kedacom/react-next'
import { useEffect, useRef, useState } from 'react'
import shallow from 'zustand/shallow'
import { useMccMtVideoStore, VrsModalBackProps } from '../store'
import { StyledUpdateVideoModalContent, StyledUpdateVideoModalFooter } from '../style'
import { regexEnum } from '@/utils'

const useModalHooks = () => {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const { vrsServerList, reload, sendCreateParam, sendStartParam, modalInfo, setModalInfo, getVrsServerList } =
		useMccMtVideoStore(
			(state) => ({
				vrsServerList: state.vrsServerList,
				sendCreateParam: state.sendCreateParam,
				sendStartParam: state.sendStartParam,
				modalInfo: state.modalInfo,
				getVrsServerList: state.getVrsServerList,
				setModalInfo: state.setModalInfo,
				reload: state.reload,
			}),
			shallow
		)
	const [vrs, setVrs] = useState<Required<VrsModalBackProps>>({
		vrs_id: '',
		rec_file: '',
		publish_mode: 1,
		vrs_name: '',
	})
	const inputRef = useRef<InnerInputRef>(null)

	const [detailInfo, setDetailInfo] = useState({
		vrsName: '',
		mtName: '',
		fileName: 'string',
		time: '',
		state: '',
		publishMode: '',
	})

	useEffect(() => {
		if (modalInfo.isShow) {
			getVrsServerList()
			if (modalInfo.type === 'detail' && modalInfo.videos[0].rec_id) {
				fetchGetVideoInfo({
					meeting_id: meetingMoid,
					id: modalInfo.videos[0].rec_id,
				}).then((res) => {
					if (res) {
						setDetailInfo(transDetailInfo(res))
					}
				})
			}
		}
	}, [modalInfo.isShow])

	useEffect(() => {
		setVrs({
			vrs_id: modalInfo.modalBack.vrs_id ?? '',
			rec_file: modalInfo.modalBack.rec_file ?? '',
			publish_mode: modalInfo.modalBack.publish_mode ?? 1, //默认发布
			vrs_name: modalInfo.modalBack.vrs_name ?? '',
		})
	}, [modalInfo])

	const transDetailInfo = (data: FetchGetVideoInfoReturnProps) => ({
		vrsName: data.vrs_name,
		mtName: data.mt.name ?? '',
		fileName: data.rec_file
			? data.rec_file.lastIndexOf('.') !== -1
				? data.rec_file.substring(0, data.rec_file.lastIndexOf('.'))
				: ''
			: '',
		time: formatSeconds(data.duration || '0'),
		state:
			data.state === 1
				? t('录像中')
				: data.state === 2
				? t('已暂停')
				: data.state === 0
				? t('已停止')
				: t('未录像'),
		publishMode: data.publish_mode ? t('已发布到视频点播') : t('未发布到视频点播'),
	})

	const onCloseModal = () => {
		setModalInfo({
			isShow: false,
		})
	}
	/**编辑操作进来的 开始录像 */
	const onUpdateStartVideo = async () => {
		if (!vrs.vrs_id) {
			Alert(t('请选择录播服务器'))
			return false
		}
		if (inputRef.current) {
			//批量不存在input输入名字
			let valid = await inputRef.current.valid()
			if (!valid) return
		}
		let params: FetchStartVideoParamsProps = {
			meeting_id: meetingMoid,
			mt_videos: [
				{
					...modalInfo.videos[0],
					publish_mode: vrs.publish_mode,
					rec_file: vrs.rec_file ? vrs.rec_file + '.asf' : '',
					vrs_id: vrs.vrs_id,
					vrs_name: vrs.vrs_name,
				},
			],
		}
		fetchStartVideo(params).then((res) => {
			if (!res.success) {
				Alert(res.description || '')
			} else {
				onCloseModal()
			}
		})
	}
	/**编辑进来的 修改再保存 */
	const onUpdateSave = async () => {
		if (!vrs.vrs_id) {
			Alert(t('请选择录播服务器'))
			return false
		}
		if (inputRef.current) {
			//批量不存在input输入名字
			let valid = await inputRef.current.valid()
			if (!valid) return
		}
		let params: FetchUpdateSaveVideoParamsProps = {
			meeting_id: meetingMoid,
			...modalInfo.videos[0],
			publish_mode: vrs.publish_mode,
			rec_file: vrs.rec_file + '.asf',
			vrs_id: vrs.vrs_id,
			vrs_name: vrs.vrs_name,
		}
		fetchUpdateSaveVideo(params).then((res) => {
			if (res.success) {
				reload()
				onCloseModal()
			} else {
				Alert(res.description || '')
			}
		})
	}
	/**创建录像 */
	const onCreateVideoSave = async () => {
		if (!vrs.vrs_id) {
			Alert(t('请选择录播服务器'))
			return false
		}
		if (inputRef.current) {
			//批量不存在input输入名字
			let valid = await inputRef.current.valid()
			if (!valid) return
		}
		let mt_videos: MtVideosProps[] = []
		modalInfo.videos.forEach((item) => {
			//过滤掉会议
			if (item.mt.mt_type !== 9) {
				const videoName = '' + replaceSpaceBk(item.mt.name || '') + buildNameTime() + '.asf'
				mt_videos.push({
					...item,
					...vrs,
					rec_file: vrs.rec_file ? vrs.rec_file + '.asf' : videoName,
					recorder_mode: 1,
				})
			}
		})
		if (useMccStore.getState().curPage !== 'mt_record') {
			useMccStore.getState().setCurPage('mt_record')
		}
		sendCreateParam(vrs, mt_videos)
	}
	/**全部终端页面下面的 【开始录像】按钮点击后 出来的弹窗的 开始确定按钮 */
	const onStartVideoSave = async () => {
		if (!vrs.vrs_id) {
			Alert(t('请选择录播服务器'))
			return false
		}
		if (inputRef.current) {
			//批量不存在input输入名字
			let valid = await inputRef.current.valid()
			if (!valid) return
		}
		let mt_videos: MtVideosProps[] = []
		modalInfo.videos.forEach((item) => {
			//过滤掉会议
			if (item.mt.mt_type !== 9) {
				const videoName = '' + replaceSpaceBk(item.mt.name || '') + buildNameTime() + '.asf'
				mt_videos.push({
					...item,
					...vrs,
					rec_file: vrs.rec_file ? vrs.rec_file + '.asf' : videoName,
					recorder_mode: 1,
				})
			}
		})
		if (useMccStore.getState().curPage !== 'mt_record') {
			useMccStore.getState().setCurPage('mt_record')
		}
		sendStartParam(vrs, mt_videos)
	}
	return {
		vrsServerList,
		vrs,
		modalInfo,
		detailInfo,
		setVrs,
		onCloseModal,
		onUpdateStartVideo,
		onUpdateSave,
		onCreateVideoSave,
		onStartVideoSave,
		inputRef,
	}
}
const WIDTH = 242
/**
 * 编辑、新建、详情终端
 * @param props
 * @returns
 */
const UpdateVideoModalView = () => {
	const { modalInfo, vrsServerList = [], inputRef, detailInfo, ...useData } = useModalHooks()
	const { type, videos } = modalInfo
	let title: string = t('终端录像')
	let footer: JSX.Element = <></>
	switch (type) {
		case 'start':
			title = t('终端录像')
			footer = (
				<>
					<Button onClick={() => useData.onStartVideoSave()}>{t('确定')}</Button>
					<Button onClick={() => useData.onCloseModal()}>{t('取消')}</Button>
				</>
			)
			break
		case 'create':
			title = t('终端录像')
			footer = (
				<>
					<Button onClick={() => useData.onCreateVideoSave()}>{t('确定')}</Button>
					<Button onClick={() => useData.onCloseModal()}>{t('取消')}</Button>
				</>
			)
			break
		case 'update':
			title = t('修改')
			footer = (
				<>
					<Button onClick={() => useData.onUpdateStartVideo()}>{t('开始录像')}</Button>
					<Button onClick={() => useData.onUpdateSave()}>{t('保存')}</Button>
					<Button onClick={() => useData.onCloseModal()}>{t('取消')}</Button>
				</>
			)
			break
		case 'detail':
			title = t('录像终端详情')
			footer = (
				<>
					<Button onClick={() => useData.onCloseModal()}>{t('关闭')}</Button>
				</>
			)
			break
		case 'terminalRecording':
			title = t('终端录像')
			footer = (
				<>
					<Button onClick={() => useData.onStartVideoSave()}>{t('开始录像')}</Button>
					<Button onClick={() => useData.onCreateVideoSave()}>{t('创建录像')}</Button>
					<Button onClick={() => useData.onCloseModal()}>{t('取消')}</Button>
				</>
			)
			break
	}
	return (
		<Modal
			open={modalInfo.isShow}
			title={title}
			width={442}
			height={type === 'detail' ? 442 : 260}
			onCancel={() => useData.onCloseModal()}
			footer={<StyledUpdateVideoModalFooter className="footer-wrap">{footer}</StyledUpdateVideoModalFooter>}
			className="update-video-modal"
		>
			<StyledUpdateVideoModalContent className="update-video-modal-wrap">
				<div className="content">
					{type !== 'detail' && (
						<Form>
							<FormItem label={t('录播服务器')}>
								<Select
									value={useData.vrs.vrs_id}
									width={WIDTH}
									valueField="vrs_id"
									labelField="server_name"
									options={[{ vrs_id: '', server_name: t('请选择') }, ...vrsServerList]}
									onClick={(e, val, opt: any, values) => {
										useData.setVrs({
											...useData.vrs,
											vrs_id: val,
											vrs_name: opt.server_name || '',
										})
									}}
								/>
							</FormItem>
							{(type === 'update' || type === 'terminalRecording') && (
								<FormItem label={t('录像文件名')}>
									<Input
										width={WIDTH}
										value={useData.vrs.rec_file}
										placeholder={t('请输入')}
										innerRef={inputRef}
										maxLength={40}
										rule={{
											required: {
												msg: t('录像文件名不能为空'),
											},
											regular: [
												{
													regex: regexEnum.videoNameIllegal,
													msg: t('录像文件名存在非法字符，请重新输入'),
												},
											],
										}}
										onChange={(e, v) => {
											useData.setVrs({
												...useData.vrs,
												rec_file: v,
											})
										}}
									/>
								</FormItem>
							)}
							<FormItem label={''}>
								<CheckBox
									checked={useData.vrs.publish_mode === 1}
									onChange={(e, v) => {
										useData.setVrs({
											...useData.vrs,
											publish_mode: v ? 1 : 0,
										})
									}}
								>
									{t('发布到视频点播')}
								</CheckBox>
							</FormItem>
						</Form>
					)}
					{type === 'detail' && (
						<Form>
							{vrsServerList.length > 1 && (
								<FormItem label={t('录播服务器')}>
									<span>{detailInfo.vrsName}</span>
								</FormItem>
							)}
							<FormItem label={t('终端名称')}>
								<span>{detailInfo.mtName}</span>
							</FormItem>
							<FormItem label={t('录像文件名')}>
								<span>{detailInfo.fileName}</span>
							</FormItem>
							<FormItem label={t('录像时长')}>
								<span>{detailInfo.time}</span>
							</FormItem>
							<FormItem label={t('录像状态')}>
								<span>{detailInfo.state}</span>
							</FormItem>
							<span>{detailInfo.publishMode}</span>
						</Form>
					)}
				</div>
			</StyledUpdateVideoModalContent>
		</Modal>
	)
}
export default UpdateVideoModalView
